﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;

namespace LiveNet.Expo
{
    internal sealed class LiveExpo : LiveNetBase<LiveExpoRequestCreator, LiveExpoAuthenticationDetails>
    {
        public LiveExpo(string applicationKey)
            : base(new LiveExpoAuthenticationDetails(applicationKey),
                   new Uri("http://expo.live.com/API/"))
        {
        }

        private Uri CreateUrl(string method)
        {
            return CreateUrl(method, new NameValueCollection());
        }
        
        private Uri CreateUrl(string method, NameValueCollection queryParameters)
        {
            queryParameters.Add("appKey", AuthenticationDetails.ApplicationKey);

            StringBuilder sb = new StringBuilder();
            foreach (string key in queryParameters)
            {
                sb.Append(string.Format("{0}={1}&", key, queryParameters[key]));
            }

            return new Uri(string.Format("{0}{1}.ashx?{2}", RootPath, method, sb.ToString().TrimEnd('&')));
        }

        public string GetSites()
        {
            Uri url = CreateUrl("Classifieds_GetSites");

            HttpWebRequest request = BuildRequest(url, "GET");

            using (HttpWebResponse httpresponse = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(httpresponse.GetResponseStream()))
                {
                    return reader.ReadToEnd();

                    // TODO: This is the response thats returned if the appKey parameter is not passed. 
                    // Although this should never happen, implement handling of it to throw an exception.
                    //"<error><errorCode>Unknown</errorCode><errorMessage>Required argument appKey missing</errorMessage></error>"
                }
            }
        }
    }
}
